<template>
    <div class="content-edit">
        <div class="page-header">
            <el-button type="primary" @click="do_edit">
                <el-icon><Document /></el-icon>
                保存
            </el-button>
            <el-button @click="router.push({path:'/main/pickup/list'})">
                <el-icon><Back /></el-icon>
                返回
            </el-button>
        </div>

        <el-form :model="info" label-width="120px" style="max-width: 800px">
            <el-form-item label="名称">
                <el-input v-model="info.name" placeholder="请输入自提点名称" />
            </el-form-item>

            <el-form-item label="电话">
                <el-input v-model="info.phone" type="tel" placeholder="请输入联系电话" />
            </el-form-item>

            <el-form-item label="省">
                <el-input v-model="info.province" placeholder="省份" />
            </el-form-item>

            <el-form-item label="市">
                <el-input v-model="info.city" placeholder="城市" />
            </el-form-item>

            <el-form-item label="区/县">
                <el-input v-model="info.area" placeholder="区/县" />
            </el-form-item>

            <el-form-item label="街道">
                <el-input v-model="info.street" placeholder="街道" />
            </el-form-item>

            <el-form-item label="详细地址">
                <el-input v-model="info.detail" placeholder="详细地址" />
            </el-form-item>

            <el-form-item label="纬度">
                <el-input v-model="info.latitude" placeholder="纬度（点击地图自动获取）" readonly />
            </el-form-item>

            <el-form-item label="经度">
                <el-input v-model="info.longitude" placeholder="经度（点击地图自动获取）" readonly />
            </el-form-item>

            <el-form-item label="状态">
                <el-select v-model="info.status" placeholder="选择状态">
                    <el-option label="启用" value="1" />
                    <el-option label="禁用" value="0" />
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="do_edit">保存</el-button>
            </el-form-item>
        </el-form>

        <!-- 地图容器 -->
        <div class="map-container">
            <div id="map-container" style="width:100%; height:600px;"></div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Document, Back } from '@element-plus/icons-vue';

const VITE_URL = window.VITE_URL;
const route = useRoute();
const router = useRouter();

const info: any = ref({
    id: 0,
    name: '',
    phone: '',
    province: '',
    city: '',
    area: '',
    street: '',
    detail: '',
    latitude: '',
    longitude: '',
    status: '1',
});

let map: any = null;
let markerLayer: any = null;

// 获取自提点信息
const pickUpInfo = () => {
    const url = VITE_URL + '/admin.pickup/single';
    const pickupId = route.params.id;

    axios.get(url, {
        params: { id: pickupId }
    }).then((res: any) => {
        info.value = res.data;
        info.value.status += ''; // 转为字符串
        mapInit();
    });
};

// 保存编辑
const do_edit = () => {
    const url = VITE_URL + '/admin.pickup/edit';

    const data: any = {
        id: info.value.id,
        name: info.value.name,
        phone: info.value.phone,
        province: info.value.province,
        city: info.value.city,
        area: info.value.area,
        street: info.value.street,
        detail: info.value.detail,
        latitude: info.value.latitude,
        longitude: info.value.longitude,
        status: info.value.status,
    };

    let dataStr = '';
    for (let p in data) {
        dataStr += p + '=' + data[p] + '&';
    }

    axios.post(url, dataStr).then((res: any) => {
        if (res.data.code == 0) {
            ElMessage({
                type: 'success',
                message: '保存成功',
                duration: 1000,
                onClose: () => {
                    router.push({ path: '/main/pickup/list' });
                }
            });
        } else {
            ElMessage.error(res.data.description || '保存失败');
        }
    });
};

// 初始化地图
const mapInit = () => {
    // 检查腾讯地图API是否加载
    if (typeof TMap === 'undefined') {
        ElMessage.warning('地图API加载中，请稍后...');
        setTimeout(mapInit, 1000);
        return;
    }

    let center = new TMap.LatLng(39.984104, 116.307503); // 默认北京
    if (info.value.latitude && info.value.longitude) {
        center = new TMap.LatLng(info.value.latitude, info.value.longitude);
    }

    // 初始化地图
    map = new TMap.Map("map-container", {
        center: center,
        zoom: 15
    });

    // 初始化marker图层
    markerLayer = new TMap.MultiMarker({
        id: 'marker-layer',
        map: map
    });

    // 如果有坐标，添加marker
    if (info.value.latitude && info.value.longitude) {
        markerLayer.add({
            position: {
                lat: info.value.latitude,
                lng: info.value.longitude,
            }
        });
    }

    // 监听点击事件添加marker
    map.on("click", (evt: any) => {
        markerLayer.setGeometries([]);
        markerLayer.add({
            position: evt.latLng
        });

        info.value.latitude = evt.latLng.lat.toFixed(6);
        info.value.longitude = evt.latLng.lng.toFixed(6);
        analyzeLocation(evt.latLng);
    });
};

// 解析坐标获取地址
const analyzeLocation = (latlng: any) => {
    const url = VITE_URL + '/admin.pickup/latlng_to_addr';

    axios.get(url, {
        params: {
            lat: latlng.lat,
            lng: latlng.lng
        }
    }).then((res: any) => {
        if (!res.data.status) {
            const addr = res.data.result;
            info.value.city = addr.address_component.city;
            info.value.area = addr.address_component.district;
            info.value.province = addr.address_component.province;
            info.value.street = addr.address_component.street;
            info.value.detail = addr.formatted_addresses.recommend;
        }
    });
};

// 加载腾讯地图API
const loadMapScript = () => {
    return new Promise((resolve, reject) => {
        if (typeof TMap !== 'undefined') {
            resolve(true);
            return;
        }

        const script = document.createElement('script');
        script.src = 'https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77';
        script.async = true;
        script.onload = () => resolve(true);
        script.onerror = () => reject(new Error('地图API加载失败'));
        document.head.appendChild(script);
    });
};

// 初始化
const init = async () => {
    info.value.id = route.params.id ? route.params.id : 0;

    // 加载地图API
    try {
        await loadMapScript();
    } catch (error) {
        ElMessage.error('地图加载失败，请刷新页面重试');
        return;
    }

    if (info.value.id) {
        pickUpInfo();
    } else {
        mapInit();
    }
};

onMounted(() => {
    init();
});
</script>

<style scoped>
.content-edit {
    padding: 20px;
}

.page-header {
    margin-bottom: 20px;
}

.map-container {
    margin-top: 30px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
}
</style>
